# 小米笔试 - 迷宫速通问题
def solve():
    t = int(input())
    for _ in range(t):
        n, m = map(int, input().split())
        
        # 读取迷宫数据
        maze = []
        for i in range(n):
            row = list(map(int, input().split()))
            maze.append(row)
        
        # dp[i][j] 表示从位置(i,j)到达终点所需的最小积分
        dp = [[0] * m for _ in range(n)]
        
        # 从右下角开始倒推
        # 终点位置：如果格子值为正数，需要0积分；如果为负数，需要1-格子的值
        dp[n-1][m-1] = max(1, 1 - maze[n-1][m-1])
        
        # 填充最后一行（只能向右）
        for j in range(m-2, -1, -1):
            dp[n-1][j] = max(1, dp[n-1][j+1] - maze[n-1][j])
        
        # 填充最后一列（只能向下）
        for i in range(n-2, -1, -1):
            dp[i][m-1] = max(1, dp[i+1][m-1] - maze[i][m-1])
        
        # 填充其他位置
        for i in range(n-2, -1, -1):
            for j in range(m-2, -1, -1):
                # 可以选择向右或向下，选择需要积分更少的路径
                right_score = dp[i][j+1] - maze[i][j]
                down_score = dp[i+1][j] - maze[i][j]
                dp[i][j] = max(1, min(right_score, down_score))
        
        print(dp[0][0])

if __name__ == "__main__":
    solve()